package com.ktgj.other.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.constant.BusinessTypeConstants;
import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.utils.SnowflakeUtils;
import com.ktgj.common.redis.service.RedisService;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.*;
import com.ktgj.other.common.TongChengUtils;
import com.ktgj.other.domain.*;
import com.ktgj.other.domain.common.*;
import com.ktgj.other.domain.vo.*;
import com.ktgj.other.mapper.*;
import com.ktgj.pay.api.RemotePayService;
import com.ktgj.pay.api.domain.*;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.other.service.IEtOrderService;

import javax.servlet.http.HttpServletRequest;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-07-22
 */
@Service
public class EtOrderServiceImpl implements IEtOrderService 
{
    private static String EtORDER = "etOrder:";
    private static String ORDER = "order:";

    @Autowired
    private EtOrderMapper etOrderMapper;
    @Autowired
    private RemoteCustomerService remoteCustomerService;
    @Autowired
    private EtOrderitemMapper etOrderitemMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private EtSceneryticketMapper etSceneryticketMapper;
    @Autowired
    private RemotePayService payService;
    @Autowired
    private EtOrderCyclerecordMapper etOrderCyclerecordMapper;
    @Autowired
    private RemotePayService remotePayService;
    @Autowired
    private EtOrderPaymentrecordMapper etOrderPaymentrecordMapper;
    @Autowired
    private EtOrderRefundrecordMapper etOrderRefundrecordMapper;
    @Autowired
    private EtOrderTrackMapper etOrderTrackMapper;
    @Autowired
    private EtSceneryticketCheckwayMapper etSceneryticketCheckwayMapper;
    @Autowired
    private EtPartnercheckwayMapper etPartnercheckwayMapper;
    @Autowired
    private EtSceneryMapper etSceneryMapper;

    /**
     * 查询【请填写功能名称】
     * 
     * @param orderid 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public EtOrder selectEtOrderById(Long orderid)
    {
        return etOrderMapper.selectEtOrderById(orderid);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param etOrder 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<EtOrder> selectEtOrderList(EtOrder etOrder)
    {
        return etOrderMapper.selectEtOrderList(etOrder);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param etOrder 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertEtOrder(EtOrder etOrder)
    {
        return etOrderMapper.insertEtOrder(etOrder);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param etOrder 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateEtOrder(EtOrder etOrder)
    {
        return etOrderMapper.updateEtOrder(etOrder);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param orderids 需要删除的【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteEtOrderByIds(Long[] orderids)
    {
        return etOrderMapper.deleteEtOrderByIds(orderids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param orderid 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteEtOrderById(Long orderid)
    {
        return etOrderMapper.deleteEtOrderById(orderid);
    }

    /**
     * 创建订单
     * */
    @Override
    public String createOrder(HttpServletRequest request, EtOrder etOrder) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();

        SnowflakeUtils snowflakeUtils = new SnowflakeUtils();

        String token = request.getHeader("token");
        Customer customer = remoteCustomerService.getLoginCustomerByToken(token).getData();
        if (customer != null){
            etOrder.setJsjid(customer.getCustomerId());
        }
        else {
            throw new Exception("登录已过期");
        }

        Long orderId = System.currentTimeMillis() / 1000;
        Long orderNum = snowflakeUtils.nextId();
        etOrder.setOrderid(orderId);

        try {
            etOrder.setTraveldate(format.parse(etOrder.getTravelTime()));
        } catch (Exception e){
            throw new Exception("出行日期格式错误");
        }

        etOrder.setOrderstatus(10l);
        etOrder.setPaystatus(10l);
        etOrder.setCreateTime(date);
        etOrder.setIsdeleted(0);
        etOrder.setOrderNum(orderNum.toString());

        if (etOrder.getTravelerVoList() != null && etOrder.getTravelerVoList().size() > 0){
            for (TravelerVo travelerVo : etOrder.getTravelerVoList()) {
                EtOrderitem etOrderitem = new EtOrderitem();
                etOrderitem.setOrderid(orderId);
                etOrderitem.setName(travelerVo.getName());
                etOrderitem.setMobile(travelerVo.getPhone());
                etOrderitem.setIdcardno(travelerVo.getLicenseNum());
                etOrderitem.setIdCardTypeId(Long.valueOf(travelerVo.getDocuments()));
                etOrderitem.setType("traveler");
                etOrderitem.setCreateTime(date);
                int i = etOrderitemMapper.insertEtOrderitem(etOrderitem);
                if (i <= 0){
                    throw new Exception("旅客信息添加失败" + travelerVo.getName());
                }
            }
        }

        if (etOrder.getObtainVoList() != null && etOrder.getObtainVoList().size() > 0){
            for (TravelerVo travelerVo : etOrder.getObtainVoList()) {
                EtOrderitem etOrderitem = new EtOrderitem();
                etOrderitem.setOrderid(orderId);
                etOrderitem.setName(travelerVo.getName());
                etOrderitem.setMobile(travelerVo.getPhone());
                etOrderitem.setIdcardno(travelerVo.getLicenseNum());
                etOrderitem.setIdCardTypeId(Long.valueOf(travelerVo.getDocuments()));
                etOrderitem.setType("obtain");
                etOrderitem.setCreateTime(date);
                int i = etOrderitemMapper.insertEtOrderitem(etOrderitem);
                if (i <= 0){
                    throw new Exception("取票人信息添加失败" + travelerVo.getName());
                }
            }
        }

        int i = etOrderMapper.insertEtOrder(etOrder);
        redisService.setCacheObject(EtORDER + etOrder.getJsjid() + ORDER + etOrder.getOrderNum(), JSON.toJSON(etOrder), 60 * 3000L, TimeUnit.SECONDS);
        if (i > 0){
            EtOrderCyclerecord etOrderCyclerecord = new EtOrderCyclerecord();
            etOrderCyclerecord.setOrderid(orderId);
            etOrderCyclerecord.setCyclerecordstatus(100l);
            etOrderCyclerecord.setCreateTime(date);
            etOrderCyclerecord.setRemark("订单提交成功，待支付订单尚未支付，请您尽快支付");
            int cyclerecord = etOrderCyclerecordMapper.insertEtOrderCyclerecord(etOrderCyclerecord);
            if (cyclerecord <= 0){
                System.out.println("添加失败");
            }
            return orderNum.toString();
        }
        else {
            throw new Exception("订单创建失败");
        }
    }

    /**
     * 门票收银台
     * */
    @Override
    public CheckoutCounterVo checkoutCounter(HttpServletRequest request, String orderNum) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String token = request.getHeader("token");
        Customer customer = remoteCustomerService.getLoginCustomerByToken(token).getData();
        if (customer == null){
            throw new Exception("登录已过期");
        }

        CheckoutCounterVo checkoutCounterVo = new CheckoutCounterVo();
        EtOrder etOrder = etOrderMapper.etOrder(orderNum);

        Long expireTime = redisService.redisTemplate.getExpire(EtORDER + customer.getCustomerId() + ORDER + orderNum);

        EtSceneryticket etSceneryticket = etSceneryticketMapper.selectEtSceneryticketById(etOrder.getSceneryticketid());
        checkoutCounterVo.setName(etSceneryticket.getTicketname());
        checkoutCounterVo.setTime(format.format(etOrder.getTraveldate()));
        checkoutCounterVo.setPayStart(etOrder.getPaystatus().toString());
        checkoutCounterVo.setCount(etOrder.getTicketcount().toString());
        checkoutCounterVo.setAmount(etOrder.getAmountprice().toString());

        if (expireTime != null && expireTime > 0){
            List<PayTypeApi> payTypes = payService.queryPayType(EmHelper.businessType.Tickets.getValue());
            for (PayTypeApi payType : payTypes) {
                PayTypeVo typeVo = new PayTypeVo();
                typeVo.setPayId(payType.getPayId());
                typeVo.setPayName(payType.getPayName());
                typeVo.setPayType(payType.getPayType());
                typeVo.setPayInfo(payType.getPayInfo());
                checkoutCounterVo.getPayTypeVoList().add(typeVo);
            }

            checkoutCounterVo.setExpired(String.valueOf(expireTime));
        }
        else {
            checkoutCounterVo.setExpired("订单已超时");
        }

        return checkoutCounterVo;
    }

    /**
     * 支付
     * */
    @Override
    public String pay(PayVo payVo, HttpServletRequest request) throws Exception {
        EtOrder etOrder = etOrderMapper.selectEtOrderById(Long.valueOf(payVo.jsjOrderId));
        BigDecimal amout = new BigDecimal(payVo.moneyAmout);
//        int i = etOrder.getAmountprice().compareTo(amout);

        payVo.moneyAmout = "0.1";
//        if (i == 0){

        String token = request.getHeader("token");
        Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
        if (employee == null){
            throw new Exception("登录已过期");
        }

        if (payVo.amount != null && payVo.amount.compareTo(new BigDecimal(0)) > 0){
            payVo.moneyAmout = String.valueOf(new BigDecimal(payVo.moneyAmout).subtract(payVo.amount));

            etOrder.setAmountprice(new BigDecimal(payVo.moneyAmout));
            etOrder.setAmount(payVo.amount);
            int i = etOrderMapper.updateEtOrder(etOrder);
            if (i <= 0){
                throw new Exception("修改订单预留款失败");
            }

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            if (payVo.type != null && payVo.type.equals("yeeBao")){
                depositBusiness.setRemark("门票银行卡支付");
            }
            else if (payVo.type != null && payVo.type.equals("voice")){
                depositBusiness.setRemark("门票语音支付");
            }
            else if (payVo.type != null && payVo.type.equals("unionPay")){
                depositBusiness.setRemark("门票二维码支付");
            }

            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.Tickets.getValue());
            depositBusiness.setOperatorId(employee.getEmployeeId());
            depositBusiness.setOrdersourceid(payVo.payType);
            depositBusiness.setCustomerId(etOrder.getJsjid());
            depositBusiness.setDetailamount(payVo.amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setAmount(payVo.amount);
            depositBusiness.setOrderId(Long.valueOf(payVo.jsjOrderId));
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款记录失败");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("id", aLong);
            if (payVo.type != null && payVo.type.equals("yeeBao")){
                map.put("remark", "门票银行卡支付");
            }
            else if (payVo.type != null && payVo.type.equals("voice")){
                map.put("remark", "门票语音支付");
            }
            else if (payVo.type != null && payVo.type.equals("unionPay")){
                map.put("remark", "门票二维码支付");
            }
            boolean b = remoteCustomerService.manageAudit(map);
            if (!b){
                throw new Exception("审核失败，请进行人工审核");
            }
        }

        if (new BigDecimal(payVo.moneyAmout).compareTo(new BigDecimal(0)) > 0){
            if (payVo.type != null && payVo.type.equals("yeeBao")){
                CustomerApi customer = new CustomerApi();
                customer.setCustCertificateNo(payVo.custCertificateNo);
                customer.setContractPhoneOne(payVo.contractPhoneOne);
                //银行卡信息
                BankCardApi card = new BankCardApi();
                card.setCardNumber(payVo.cardNumber);
                card.setCardholder(payVo.cardholder);

                Map<String, Object> map = new HashMap<>();
                map.put("cardNumber", payVo.cardNumber);
                String backCard = remoteCustomerService.backCard(map);

                card.bankCode = backCard + "CREDIT";
                if (payVo.creditCardTime != null && !payVo.creditCardTime.equals("") &&
                        payVo.Cvv2 != null && !payVo.Cvv2.equals("")){
                    card.setCreditCardTime(payVo.creditCardTime);
                    card.setCvv2(payVo.Cvv2);
                }

                BankPayInfoApi bankPayInfoApi = new BankPayInfoApi();
                bankPayInfoApi.setJsjOrderId(payVo.jsjOrderId);
                bankPayInfoApi.setMoneyAmout(payVo.moneyAmout);
                bankPayInfoApi.setCustomer(customer);
                bankPayInfoApi.setCard(card);
                bankPayInfoApi.setPayType(payVo.payType);

                YeeBaoResultApi yeeBaoResultApi;
                if (payVo.creditCardTime != null && !payVo.creditCardTime.equals("") &&
                        payVo.Cvv2 != null && !payVo.Cvv2.equals("")){
                    yeeBaoResultApi = remotePayService.CreditSale(bankPayInfoApi);
                }
                else {
                    yeeBaoResultApi = remotePayService.DebitSale(bankPayInfoApi);
                }
                if (yeeBaoResultApi.getCode().equals("1")){

                    if (payVo.jsjOrderId != null) {
                        etOrder.setPaystatus(20l);
                        int i = etOrderMapper.updateEtOrder(etOrder);
                        if (i <= 0){
                            throw new Exception("订单支付状态修改失败");
                        }

                        EtOrderCyclerecord etOrderCyclerecord = new EtOrderCyclerecord();
                        etOrderCyclerecord.setOrderid(etOrder.getOrderid());
                        etOrderCyclerecord.setCyclerecordstatus(101l);
                        etOrderCyclerecord.setCreateTime(new Date());
                        etOrderCyclerecord.setRemark("订单支付成功");
                        i = etOrderCyclerecordMapper.insertEtOrderCyclerecord(etOrderCyclerecord);
                        if (i <= 0){
                            throw new Exception("添加订单支付记录失败");
                        }

                        EtOrderPaymentrecord etOrderPaymentrecord = new EtOrderPaymentrecord();
                        etOrderPaymentrecord.setOrderid(etOrder.getOrderid());
                        etOrderPaymentrecord.setBankcardnumber(payVo.cardNumber);
                        etOrderPaymentrecord.setBankcardholdername(payVo.cardholder);
                        if (payVo.creditCardTime != null && !payVo.creditCardTime.equals("") &&
                                payVo.Cvv2 != null && !payVo.Cvv2.equals("")){
                            etOrderPaymentrecord.setPaymenttype(EmHelper.cardType.CREDIT_CARD.getValue());
                        }
                        else {
                            etOrderPaymentrecord.setPaymenttype(EmHelper.cardType.DEBIT_CARD.getValue());
                        }
                        etOrderPaymentrecord.setPaymentstatus("20");
                        etOrderPaymentrecord.setRemark("门票订单-订单号" + etOrder.getOrderNum() + "，支付金额-" + etOrder.getAmountprice());
                        etOrderPaymentrecord.setCreateTime(new Date());
                        etOrderPaymentrecord.setUpdateTime(new Date());
                        etOrderPaymentrecord.setTransactionnumber(yeeBaoResultApi.getTrxId());
                        i = etOrderPaymentrecordMapper.insertEtOrderPaymentrecord(etOrderPaymentrecord);
                        if (i <= 0){
                            throw new Exception("添加支付信息失败");
                        }

                        HttpTongChengInfoOrder httpTongChengInfoOrder = orderPlace(etOrder.getOrderNum());
                        if (httpTongChengInfoOrder.getRespCode() != 1){
                            throw new Exception(httpTongChengInfoOrder.getRespMsg());
                        }
                        else {
                            etOrder.setPartnerordernumber(httpTongChengInfoOrder.getSerialId());
                            etOrderMapper.updateEtOrder(etOrder);
                        }
                    }
                    return "支付成功";
                }
                else {
                    etOrder.setPaystatus(30l);
                    int i = etOrderMapper.updateEtOrder(etOrder);
                    if (i <= 0){
                        throw new Exception("订单支付状态修改失败");
                    }

                    EtOrderCyclerecord etOrderCyclerecord = new EtOrderCyclerecord();
                    etOrderCyclerecord.setOrderid(etOrder.getOrderid());
                    etOrderCyclerecord.setCyclerecordstatus(0l);
                    etOrderCyclerecord.setCreateTime(new Date());
                    etOrderCyclerecord.setRemark("订单支付失败：" + yeeBaoResultApi.getErrorMsg());
                    i = etOrderCyclerecordMapper.insertEtOrderCyclerecord(etOrderCyclerecord);
                    if (i <= 0){
                        throw new Exception("添加订单支付记录失败");
                    }

                    EtOrderPaymentrecord etOrderPaymentrecord = new EtOrderPaymentrecord();
                    etOrderPaymentrecord.setOrderid(etOrder.getOrderid());
                    etOrderPaymentrecord.setBankcardnumber(payVo.cardNumber);
                    etOrderPaymentrecord.setBankcardholdername(payVo.cardholder);
                    if (payVo.creditCardTime != null && !payVo.creditCardTime.equals("") &&
                            payVo.Cvv2 != null && !payVo.Cvv2.equals("")){
                        etOrderPaymentrecord.setPaymenttype(EmHelper.cardType.CREDIT_CARD.getValue());
                    }
                    else {
                        etOrderPaymentrecord.setPaymenttype(EmHelper.cardType.DEBIT_CARD.getValue());
                    }
                    etOrderPaymentrecord.setPaymentstatus("10");
                    etOrderPaymentrecord.setCreateTime(new Date());
                    etOrderPaymentrecord.setUpdateTime(new Date());
                    i = etOrderPaymentrecordMapper.insertEtOrderPaymentrecord(etOrderPaymentrecord);
                    if (i <= 0){
                        throw new Exception("添加支付信息失败");
                    }

                    return yeeBaoResultApi.getErrorMsg();
                }
            }
            else if (payVo.type != null && payVo.type.equals("voice")){
                Map<String, Object> voice = new HashMap<>();
                voice.put("mobileNumber", payVo.contractPhoneOne);
                voice.put("bankCardNo", payVo.cardNumber);
                voice.put("idCardNo", payVo.custCertificateNo);
                voice.put("idCardName", payVo.cardholder);
                int parseInt = Integer.parseInt(payVo.moneyAmout) * 100;
                voice.put("orderAmount", parseInt);
                voice.put("orderId", payVo.jsjOrderId);
                voice.put("asynAddress", "http://106.38.39.137:8080/other/callback/otherVoicePayCallback");

                String voicePay = remotePayService.voicePay(voice);

                String newVoicePay = "支付失败";
                if (voicePay != null){
                    newVoicePay = voicePay.substring(0, voicePay.indexOf(","));
//                String voicePayNew = voicePay.substring(voicePay.indexOf(",") + 1);
                    if (newVoicePay.equals("请注意来电")){

                        EtOrderCyclerecord etOrderCyclerecord = new EtOrderCyclerecord();
                        etOrderCyclerecord.setOrderid(etOrder.getOrderid());
                        etOrderCyclerecord.setCyclerecordstatus(100l);
                        etOrderCyclerecord.setCreateTime(new Date());
                        etOrderCyclerecord.setRemark("订单支付成功，等待确认订单已支付成功");
                        int i = etOrderCyclerecordMapper.insertEtOrderCyclerecord(etOrderCyclerecord);
                        if (i <= 0){
                            throw new Exception("添加订单支付记录失败");
                        }

                        EtOrderPaymentrecord etOrderPaymentrecord = new EtOrderPaymentrecord();
                        etOrderPaymentrecord.setOrderid(etOrder.getOrderid());
                        etOrderPaymentrecord.setBankcardnumber(payVo.cardNumber);
                        etOrderPaymentrecord.setBankcardholdername(payVo.cardholder);
                        etOrderPaymentrecord.setPaymenttype(EmHelper.cardType.Voice.getValue());
                        etOrderPaymentrecord.setCreateTime(new Date());
                        etOrderPaymentrecord.setUpdateTime(new Date());
                        i = etOrderPaymentrecordMapper.insertEtOrderPaymentrecord(etOrderPaymentrecord);
                        if (i <= 0){
                            throw new Exception("添加支付信息失败");
                        }

                        return newVoicePay;
                    }
                    else {
                        etOrder.setMsg("语音支付失败");
                        int i = etOrderMapper.updateEtOrder(etOrder);
                        if (i <= 0){
                            throw new Exception("记录错误信息失败");
                        }
                        return "支付失败";
                    }
                }
                else {
                    return null;
                }
            }
            else if (payVo.type != null && payVo.type.equals("unionPay")){
                String billNo = payVo.jsjOrderId;
                String totalAmount = payVo.moneyAmout;
                String notifyUrl = "http://106.38.39.137:8080/other/callback/otherUnionQRCodePayCallback";
                Map<String, String> map = new HashMap<>();
                BigDecimal amount = new BigDecimal(billNo);
                billNo = "5676" + amount;
                map.put("billNo", billNo);
                map.put("totalAmount", String.valueOf(new BigDecimal(totalAmount).multiply(new BigDecimal(100)).longValue()));
                map.put("notifyUrl", notifyUrl);
                UnionPayQRCodeResponseApi qrCode = remotePayService.getQRCode(map);
                if (qrCode.getBillQRCode() != null && !qrCode.getBillQRCode().equals("")){

                    EtOrderCyclerecord etOrderCyclerecord = new EtOrderCyclerecord();
                    etOrderCyclerecord.setOrderid(etOrder.getOrderid());
                    etOrderCyclerecord.setCyclerecordstatus(100l);
                    etOrderCyclerecord.setCreateTime(new Date());
                    etOrderCyclerecord.setRemark("订单支付成功，等待确认订单已支付成功");
                    int i = etOrderCyclerecordMapper.insertEtOrderCyclerecord(etOrderCyclerecord);
                    if (i <= 0){
                        throw new Exception("添加订单支付记录失败");
                    }

                    EtOrderPaymentrecord etOrderPaymentrecord = new EtOrderPaymentrecord();
                    etOrderPaymentrecord.setOrderid(etOrder.getOrderid());
                    etOrderPaymentrecord.setBankcardnumber(payVo.cardNumber);
                    etOrderPaymentrecord.setBankcardholdername(payVo.cardholder);
                    etOrderPaymentrecord.setPaymenttype(EmHelper.cardType.UnionPayQR.getValue());
                    etOrderPaymentrecord.setCreateTime(new Date());
                    etOrderPaymentrecord.setUpdateTime(new Date());
                    i = etOrderPaymentrecordMapper.insertEtOrderPaymentrecord(etOrderPaymentrecord);
                    if (i <= 0){
                        throw new Exception("添加支付信息失败");
                    }

                    return qrCode.getBillQRCode();
                }
                else {
                    return qrCode.getErrMsg();
                }
            }
            else {
                throw new Exception("无效的支付类型");
            }
        }
        else {
            return "支付成功";
        }
//        }
//        else {
//            return "支付金额发生变化";
//        }
    }

    /**
     * 门票小程序支付
     * */
    @Override
    public Map<String, Object> etOrderPay(String orderNumber, String openId, HttpServletRequest request, BigDecimal amount, String type) throws Exception {
        EtOrder etOrder = etOrderMapper.etOrder(orderNumber);

        String token = request.getHeader("token");
        Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
        if (employee != null){
            throw new Exception("登录已过期");
        }

        if (amount.compareTo(new BigDecimal(0)) > 0){
            etOrder.setAmountprice(etOrder.getAmountprice().subtract(amount));

            etOrder.setAmount(amount);
            int i = etOrderMapper.updateEtOrder(etOrder);
            if (i <= 0){
                throw new Exception("修改订单预留款失败");
            }

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("门票小程序支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.Tickets.getValue());
            depositBusiness.setOperatorId(employee.getEmployeeId());
            depositBusiness.setOrdersourceid(type);
            depositBusiness.setCustomerId(etOrder.getJsjid());
            depositBusiness.setDetailamount(amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(Long.valueOf(orderNumber));
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款记录失败");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("id", aLong);
            map.put("remark", "门票小程序支付");
            boolean b = remoteCustomerService.manageAudit(map);
            if (!b){
                throw new Exception("审核失败，请进行人工审核");
            }
        }

        String notifyUrl = "/other/callback/hotelWechatPayCallback";
        R<Map> wechatJSAPIPayParam = payService.getWechatJSAPIPayParam(openId, etOrder.getAmountprice(), orderNumber, notifyUrl);
        if (wechatJSAPIPayParam.getCode() == 200) {
            return wechatJSAPIPayParam.getData();
        }
        return null;
    }

    /**
     * 门票下单
     * */
    @Override
    public HttpTongChengInfoOrder orderPlace(String orderNum) throws Exception {
        EtOrder etOrder = etOrderMapper.etOrder(orderNum);

        CustomerIdVoApi customerIdVoApi = new CustomerIdVoApi();
        customerIdVoApi.setCustomerId(etOrder.getJsjid());
        customerIdVoApi = remoteCustomerService.customerIdApi(customerIdVoApi);

        List<EtOrderitem> obtain = etOrderitemMapper.obtain(etOrder.getOrderid());

        EtSceneryticket etSceneryticket = etSceneryticketMapper.selectEtSceneryticketById(etOrder.getSceneryticketid());

        HttpTongChengInfoDate verify = verify(etSceneryticket, etOrder, obtain);

        if (verify.getRespCode() != 1){
            throw new Exception("验证失败");
        }

        TongChengUtils tongChengUtils = new TongChengUtils();

        TongChengInfoOrder tongChengInfoOrder = new TongChengInfoOrder();

        RequestBodyOrder requestBody = new RequestBodyOrder();

        List<Integer> ticketsNum = new ArrayList<>();
        ticketsNum.add(Integer.parseInt(etOrder.getTicketcount().toString()));
        requestBody.setTicketsNum(ticketsNum);

        List<String> bookMan = new ArrayList<>();
        bookMan.add(customerIdVoApi.getCustomerName());
        requestBody.setBookMan(bookMan);

        requestBody.setBookMobileType(1);

        List<String> bookMobile = new ArrayList<>();
        bookMobile.add(customerIdVoApi.getCustomerPhone());
        requestBody.setBookMobile(bookMobile);

        List<String> travelerName = new ArrayList<>();
        List<String> travelerMobile = new ArrayList<>();
        List<String> travelerIdCardNoList = new ArrayList<>();
        List<String> travelerCerTypeList = new ArrayList<>();
        for (EtOrderitem etOrderitem : obtain) {
            travelerName.add(etOrderitem.getName());
            travelerMobile.add(etOrderitem.getMobile());
            travelerIdCardNoList.add(etOrderitem.getIdcardno());
            travelerCerTypeList.add(etOrderitem.getIdCardTypeId().toString());
        }
        requestBody.setTravelerName(travelerName);
        requestBody.setTravelerMobile(travelerMobile);
        requestBody.setTravelerIdCardNoList(travelerIdCardNoList);
        requestBody.setTravelerCerTypeList(travelerCerTypeList);

        requestBody.setTravelerMobileType(1);
        requestBody.setTravelerIdCardNo(obtain.get(0).getIdcardno());
        requestBody.setTravelerCerType(obtain.get(0).getIdCardTypeId().toString());
        requestBody.setPriceID(Integer.parseInt(etSceneryticket.getEtsceneryid().toString()));
        requestBody.setTravelDate(etOrder.getTraveldate());

        List<String> thirdSerialId = new ArrayList<>();
        thirdSerialId.add(etOrder.getOrderNum());
        requestBody.setThirdSerialId(thirdSerialId);
        tongChengInfoOrder.setRequestBody(requestBody);

        HttpTongChengInfoOrder orderService = tongChengUtils.createOrderService(tongChengInfoOrder);
        return orderService;
    }

    /**
     * 门票订单列表
     * */
    @Override
    public List<EtOrder> attractionsOrderList(HttpServletRequest request, String type) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String token = request.getHeader("token");
        Customer customer = remoteCustomerService.getLoginCustomerByToken(token).getData();
        if (customer == null){
            throw new Exception("登录已过期");
        }

        List<EtOrder> etOrderList = etOrderMapper.attractionsOrderList(customer.getCustomerId(), type);
        if (etOrderList != null && etOrderList.size() > 0){
            for (EtOrder etOrder : etOrderList) {
                if (etOrder.getPaystatus() == 10){
                    etOrder.setStart("未支付");
                }
                else if (etOrder.getPaystatus() == 20){
                    if (etOrder.getOrderstatus() == 10){
                        etOrder.setStart("未出行");
                    }
                    else if (etOrder.getOrderstatus() == 20){
                        etOrder.setStart("已出行");
                    }
                    else if (etOrder.getOrderstatus() == 40){
                        etOrder.setStart("已取消");
                    }
                    else {
                        etOrder.setStart("已删除");
                    }
                }
                else {
                    etOrder.setStart("支付失败");
                }

                EtSceneryticket etSceneryticket = etSceneryticketMapper.selectEtSceneryticketById(etOrder.getSceneryticketid());
                etOrder.setTickets(etSceneryticket.getTicketname());

                if (etOrder.getTraveldate() != null){
                    etOrder.setTravelTime(format.format(etOrder.getTraveldate()));
                }
            }
        }

        return etOrderList;
    }

    /**
     * 申请退票
     * */
    @Override
    public HttpTongChengInfoCancel applyRefund(ApplyRefundVo applyRefundVo, HttpServletRequest request) throws Exception {
        TongChengUtils tongChengUtils = new TongChengUtils();
        EtOrder etOrder = etOrderMapper.selectEtOrderById(applyRefundVo.getOrderId());

        String token = request.getHeader("token");
        Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
        if (employee == null){
            throw new Exception("登录已过期");
        }

        DepositBusinessApi depositBusiness = new DepositBusinessApi();
        depositBusiness.setRemark("门票退票");
        depositBusiness.setState("false");
        depositBusiness.setBusinessType(EmHelper.businessType.Tickets.getValue());
        depositBusiness.setOperatorId(employee.getEmployeeId());
        depositBusiness.setOrdersourceid(applyRefundVo.getType());
        depositBusiness.setCustomerId(etOrder.getJsjid());
        depositBusiness.setDetailamount(etOrder.getAmount());
        depositBusiness.setChangetype(1l);
        depositBusiness.setLockState("false");
        depositBusiness.setOrderId(Long.valueOf(etOrder.getOrderNum()));
        depositBusiness.setDrawState("true");
        Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
        if (aLong <= 0){
            throw new Exception("添加预留款记录失败");
        }

        TongChengInfoCancel tongChengInfoCancel = new TongChengInfoCancel();

        RequestBodyCancel requestBodyCancel = new RequestBodyCancel();
        requestBodyCancel.setSerialId(etOrder.getPartnerordernumber());
        requestBodyCancel.setRefundTicketsNum(applyRefundVo.getTravelerIdList().size());
        requestBodyCancel.setRefundType(0);
        requestBodyCancel.setRefundReasonId(Integer.parseInt(applyRefundVo.getRefundReasonId().toString()));

        tongChengInfoCancel.setRequestBody(requestBodyCancel);
        HttpTongChengInfoCancel httpTongChengInfoCancel = tongChengUtils.newCreateOrderCancelService(tongChengInfoCancel);

        EtOrderRefundrecord etOrderRefundrecord = new EtOrderRefundrecord();
        etOrderRefundrecord.setOrderid(applyRefundVo.getOrderId());
        etOrderRefundrecord.setTicketcount(Long.valueOf(applyRefundVo.getTravelerIdList().size()));
        etOrderRefundrecord.setApplytime(new Date());
        etOrderRefundrecord.setIsdispose(0l);

        EtOrderTrack etOrderTrack = new EtOrderTrack();
        etOrderTrack.setOrderid(applyRefundVo.getOrderId());
        etOrderTrack.setTitle("提交申请");
        etOrderTrack.setCreateTime(new Date());

        if (httpTongChengInfoCancel.getRespCode() != 1){
            etOrderRefundrecord.setFailedreason(httpTongChengInfoCancel.getRespMsg());
            etOrderTrack.setContents("退款申请提交失败");
            etOrderRefundrecord.setRefundstatus(32l);
        }
        else {
            etOrderRefundrecord.setRefundstatus(31l);
            etOrderTrack.setContents("退款申请已经成功提交");
        }

        int i = etOrderRefundrecordMapper.insertEtOrderRefundrecord(etOrderRefundrecord);
        if (i <= 0){
            throw new Exception("添加退款信息失败");
        }

        i = etOrderTrackMapper.insertEtOrderTrack(etOrderTrack);
        if (i <= 0){
            throw new Exception("添加退款流程-申请失败");
        }

        if (httpTongChengInfoCancel.getRespCode() == 1){
            etOrderTrack.setContents("景区审核退款申请中");
            etOrderTrack.setCreateTime(new Date());
            etOrderTrack.setTitle("景区处理");
            i = etOrderTrackMapper.insertEtOrderTrack(etOrderTrack);
            if (i <= 0){
                throw new Exception("添加退款流程-处理失败");
            }
        }

        return httpTongChengInfoCancel;
    }

    /**
     * 订单详情
     * */
    @Override
    public OrderDetailsVo orderDetails(Long id) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        EtOrder etOrder = etOrderMapper.selectEtOrderById(id);
        EtSceneryticket etSceneryticket = etSceneryticketMapper.selectEtSceneryticketById(etOrder.getSceneryticketid());
        List<EtOrderitem> traveler = etOrderitemMapper.traveler(etOrder.getOrderid());
        List<EtSceneryticketCheckway> etSceneryticketCheckways = etSceneryticketCheckwayMapper.sceneryticketCheckwayList(etSceneryticket.getSceneryticketid());
        EtScenery etScenery = etSceneryMapper.selectEtSceneryById(etSceneryticket.getEtsceneryid());
        EtOrderCyclerecord etOrderCyclerecord = etOrderCyclerecordMapper.payTime(etOrder.getOrderid());
        EtOrderPaymentrecord etOrderPaymentrecord = etOrderPaymentrecordMapper.orderPaymentrecord(etOrder.getOrderid());

        OrderDetailsVo orderDetailsVo = new OrderDetailsVo();
        if (etOrder.getPaystatus() == 10){
            orderDetailsVo.setOrderStart("未支付");
        }
        else if (etOrder.getPaystatus() == 20){
            if (etOrder.getOrderstatus() == 10){
                orderDetailsVo.setOrderStart("未出行");
            }
            else if (etOrder.getOrderstatus() == 20){
                orderDetailsVo.setOrderStart("已出行");
            }
            else if (etOrder.getOrderstatus() == 40){
                orderDetailsVo.setOrderStart("已取消");
            }
        }
        else if (etOrder.getPaystatus() == 20){
            orderDetailsVo.setOrderStart("支付失败");
        }

        orderDetailsVo.setOrderNum(etOrder.getOrderNum());
        orderDetailsVo.setTicketsName(etSceneryticket.getTicketname());
        orderDetailsVo.setTime(format.format(etOrder.getTraveldate()));

        BigDecimal divide = etOrder.getPayableamount().divide(new BigDecimal(traveler.size()));
        orderDetailsVo.setAmount(divide.toString());
        orderDetailsVo.setTicketsCount(Long.valueOf(traveler.size()));

        if (etSceneryticketCheckways != null && etSceneryticketCheckways.size() > 0){
            for (int i = 0; i < etSceneryticketCheckways.size(); i++) {
                EtPartnercheckway etPartnercheckway = etPartnercheckwayMapper.selectEtPartnercheckwayById(etSceneryticketCheckways.get(i).getPartnercheckwayid());

                if (i == 0){
                    orderDetailsVo.setWay(etPartnercheckway.getPartnercheckwayname());
                }
                else {
                    orderDetailsVo.setWay(orderDetailsVo.getWay() + "," + etPartnercheckway.getPartnercheckwayname());
                }
            }
        }
        orderDetailsVo.setScenicSpotName(etScenery.getName());
        orderDetailsVo.setScenicSpotAddress(etScenery.getAddress());
        orderDetailsVo.setBusinessHours(etScenery.getBusinesshours());

        List<TicketCollectorVo> ticketCollectorVoList = new ArrayList<>();
        for (EtOrderitem etOrderitem : traveler) {
            TicketCollectorVo ticketCollectorVo = new TicketCollectorVo();
            ticketCollectorVo.setName(etOrderitem.getName());
            ticketCollectorVo.setPhone(etOrderitem.getMobile());
        }
        orderDetailsVo.setTicketCollectorVoList(ticketCollectorVoList);
        orderDetailsVo.setOrderTime(format.format(etOrder.getCreateTime()));
        orderDetailsVo.setPayTime(format.format(etOrderCyclerecord.getCreateTime()));

        if (etOrderPaymentrecord.getPaymenttype().equals(EmHelper.cardType.CREDIT_CARD.getValue())){
            orderDetailsVo.setPayType("信用卡");
        }
        else if (etOrderPaymentrecord.getPaymenttype().equals(EmHelper.cardType.DEBIT_CARD.getValue())){
            orderDetailsVo.setPayType("借记卡");
        }
        else if (etOrderPaymentrecord.getPaymenttype().equals(EmHelper.cardType.UnionPayQR.getValue())){
            orderDetailsVo.setPayType("银联二维码");
        }
        else if (etOrderPaymentrecord.getPaymenttype().equals(EmHelper.cardType.Voice.getValue())){
            orderDetailsVo.setPayType("语音");
        }
        else if (etOrderPaymentrecord.getPaymenttype().equals(EmHelper.cardType.Applets.getValue())){
            orderDetailsVo.setPayType("微信小程序");
        }
        orderDetailsVo.setLumpSum(etOrder.getMarketprice().toString());

        EtOrderRefundrecord etOrderRefundrecord = etOrderRefundrecordMapper.orderRefundrecord(etOrder.getOrderid());
        if (etOrderRefundrecord != null){
            if (etOrderRefundrecord.getPoundageamount() != null && etOrderRefundrecord.getJsjpoundageamount() != null){
                BigDecimal handlingFee = etOrderRefundrecord.getPoundageamount().add(etOrderRefundrecord.getJsjpoundageamount());
                orderDetailsVo.setHandlingFee(handlingFee.toString());

                BigDecimal refundAmount = etOrderRefundrecord.getRefundamount().subtract(etOrderRefundrecord.getJsjpoundageamount());
                orderDetailsVo.setRefundAmount(refundAmount.toString());
            }

            if (etOrderRefundrecord.getTicketcount() != null){
                orderDetailsVo.setRefundCount(etOrderRefundrecord.getTicketcount());
            }

            if (etOrderRefundrecord.getRefundamount() != null && etOrderRefundrecord.getPoundageamount() != null){
                BigDecimal refundLumpSum = etOrderRefundrecord.getRefundamount().add(etOrderRefundrecord.getPoundageamount());
                orderDetailsVo.setRefundLumpSum(refundLumpSum.toString());

                RefundDetailsVo refundDetailsVo = new RefundDetailsVo();
                refundDetailsVo.setRefundLumpSum(refundLumpSum.toString());
                refundDetailsVo.setRefundCount(etOrderRefundrecord.getTicketcount());

                BigDecimal unitPrice = refundLumpSum.divide(new BigDecimal(etOrderRefundrecord.getTicketcount()));
                refundDetailsVo.setUnitPrice(unitPrice.toString());

                BigDecimal handlingFee = etOrderRefundrecord.getPoundageamount().add(etOrderRefundrecord.getJsjpoundageamount());
                handlingFee = handlingFee.divide(new BigDecimal(etOrderRefundrecord.getTicketcount()));
                refundDetailsVo.setHandlingFee(handlingFee.toString());
                orderDetailsVo.setRefundDetailsVo(refundDetailsVo);
            }
        }

        if (etOrder.getAmountprice() != null){
            orderDetailsVo.setActuallyPaid(etOrder.getAmountprice().toString());
        }

        return orderDetailsVo;
    }

    /**
     * 退款规则
     * */
    @Override
    public HttpTongChengInfoRule refundPolicy(Long id) {
        TongChengUtils tongChengUtils = new TongChengUtils();
        TongChengInfoRule tongChengInfoRule = new TongChengInfoRule();
        RequestBodyRule requestBodyRule = new RequestBodyRule();
        requestBodyRule.setProductID(Integer.parseInt(id.toString()));
        requestBodyRule.setViewSceneryRule(true);
        tongChengInfoRule.setRequestBody(requestBodyRule);
        HttpTongChengInfoRule refundRuleService = tongChengUtils.getRefundRuleService(tongChengInfoRule);
        return refundRuleService;
    }

    /**
     * 下单验证
     * */
    public HttpTongChengInfoDate verify(EtSceneryticket etSceneryticket, EtOrder etOrder, List<EtOrderitem> obtain){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        TongChengUtils tongChengUtils = new TongChengUtils();

        TongChengInfoDate tongChengInfoDate = new TongChengInfoDate();
        RequestBodyDate requestBody = new RequestBodyDate();
        requestBody.setPriceId(Integer.parseInt(etSceneryticket.getTicketpriceid().toString()));
        requestBody.setTravelDate(format.format(etOrder.getTraveldate()));
        requestBody.setTickets(Integer.parseInt(etOrder.getTicketcount().toString()));
        requestBody.setTravelerIdCardNoType(Integer.parseInt(obtain.get(0).getIdCardTypeId().toString()));
        requestBody.setTravelerIdCardNo(obtain.get(0).getIdcardno());
        requestBody.setTravelerMobile(obtain.get(0).getMobile());
        requestBody.setMobileIdentifier("");//预定人手机号码识别码

        List<RealBookInfo> RealBookInfo = new ArrayList<>();

        for (EtOrderitem etOrderitem : obtain) {
            RealBookInfo realBookInfo = new RealBookInfo();
            realBookInfo.setName(etOrderitem.getName());
            realBookInfo.setMobile(etOrderitem.getMobile());
            realBookInfo.setIdCardType(Integer.parseInt(etOrderitem.getIdCardTypeId().toString()));
            realBookInfo.setIdCard(etOrderitem.getIdcardno().toString());
            realBookInfo.setTCAmount(etOrder.getPayableamount().toString());
            RealBookInfo.add(realBookInfo);
        }

        requestBody.setRealBookInfo(RealBookInfo);
        tongChengInfoDate.setRequestBody(requestBody);
        HttpTongChengInfoDate orderValidateService = tongChengUtils.createOrderValidateService(tongChengInfoDate);
        return orderValidateService;
    }
}
